package cn.wolfcode.luowowo2.comment.service.impl;

import cn.wolfcode.luowowo2.cache.domain.TravelComment;
import cn.wolfcode.luowowo2.cache.repository.ITravelCommentRepository;
import cn.wolfcode.luowowo2.cache.service.ITravelCommentService;
import cn.wolfcode.luowowo2.common.query.TravelCommentQueryObject;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

/**
 * Created by Albert on 2019/7/12.
 */
@Service
public class TravelCommentServiceImpl implements ITravelCommentService{
    @Autowired
    private ITravelCommentRepository dao;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public TravelComment save(TravelComment travelComment) {
        //保存之前需要先获取引用的comment
        if (travelComment.getRefComment()!=null && StringUtils.hasLength(travelComment.getRefComment().getId())) {
            Optional<TravelComment> refCommentOptional = dao.findById(travelComment.getRefComment().getId());
            TravelComment refTravelComment = refCommentOptional.get();
            travelComment.setRefComment(refTravelComment);
        }
        TravelComment savedComment = dao.save(travelComment);
        return savedComment;
    }

    @Override
    public Page<TravelComment> query(TravelCommentQueryObject qo) {
        Query query = new Query();
        Criteria criteria = null;
        if (qo.getTravelId()==-1L) {
            criteria = Criteria.where("travelId").ne(qo.getTravelId());
        }else {
            criteria = Criteria.where("travelId").is(qo.getTravelId());
        }

        query.addCriteria(criteria);

        long count = mongoTemplate.count(query,TravelComment.class);
        if (count==0) {
            return Page.empty();
        }

        Sort sort = Sort.by(Sort.Direction.ASC, "createTime");
        query.with(sort);
        List<TravelComment> list = mongoTemplate.find(query, TravelComment.class);
        return new PageImpl<TravelComment>(list);
    }
}
